<?php

include_once 'user.php';
include_once '../utils/constants.php';
include_once '../utils/debug.php';
include_once '../utils/utils.php';

class Users {

	/**
	 * array of User objects
	 */
	private $usersArray = array();

	public function Users($filename) {
		if (DEBUG) enter("Users::Users($filename)");
		$content = file_get_contents($filename);
		$usersStringArray = split("\n", $content);
		if (DEBUG) {
			debug("Users::Users(), usersStringArray=");
			var_dump($usersStringArray);
		}
		foreach ($usersStringArray as $userString) {
			if (DEBUG) debug("Users::Users(), user string: $userString");
			$us = new User();
			array_push($this->usersArray, $us->buildFromString(trim($userString)));
		}
		if (DEBUG) {
			debug("Users::Users(), usersArray=");
			var_dump($this->usersArray);
		}
		if (DEBUG) ex("Users::Users()");
	}

	public function getUsers() {
		if (DEBUG) enex("Users::getUsers()");
		return $this->usersArray;
	}

	/**
	 * Comparator
	 *
	 * @param User $a
	 * @param User $b
	 * @return int, if $a = $b, return 0, if $a > $b return -1, else 1
	 */
	static function compareUsers($a, $b) {
		if ($a->getScore() == $b->getScore()) {
			return 0;
		}
		return ($a->getScore() < $b->getScore()) ? 1 : -1;
	}

	/**
	 * return an array of User objects sorted by Score property
	 */
	public function getUsersSorted() {
		if (DEBUG) enter("Users::getUsersSorted()");
		$sorted = $this->usersArray;
		usort($sorted, array(&$this, "compareUsers")); //special trick to use comparator within class
		if (DEBUG) ex("Users::getUsersSorted()");
		return $sorted;
	}

	public function addUser($user) {
		if (DEBUG) enex("Users::addUser($user)");
		array_push($this->usersArray, $user);
	}

	/**
	 * Checks if user with given name exists in user array
	 *
	 * @param string $userName
	 * @return true if exist, false otherwise
	 */
	public function exist($userName) {
		$index = array_search($userName, $this->usersArray);
		foreach ($this->usersArray as $user) {
			if ($user->getLogin == $userName) {
				return true;
			}
		}
		return false;
	}

	public function removeUser($user) {
		if (DEBUG) enter("Users::removeUser()");
		$index = array_search($user, $this->usersArray);
		if ($index !== false) {
			unset($this->usersArray[$index]);
		}
		if (DEBUG) ex("Users::removeUser()");
	}
}

?>